package com.pengtu.gsj.service.impl.system;

import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserCache;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.core.userdetails.cache.NullUserCache;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Sets;
import com.pengtu.gsj.dao.system.BannerDao;
import com.pengtu.gsj.dao.system.UserDao;
import com.pengtu.gsj.entity.app.Role;
import com.pengtu.gsj.entity.app.Sysmenu;
import com.pengtu.gsj.entity.app.User;



/**
 * 实现SpringSecurity的UserDetailsService接口,实现获取用户Detail信息的回调函数.
 * 
 * @author calvin
 */
@Transactional(readOnly = true)
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
	private UserCache userCache = new NullUserCache();
	@Autowired
	private UserDao userDao;
	@Autowired
	private BannerDao bannerDao;

	public UserCache getUserCache() {
		return userCache;
	}
	public void setUserCache(UserCache userCache) {
		this.userCache = userCache;
	}
	/**
	 * 获取用户Details信息的回调函数.
	 */
    @Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
    	UserDetails user = userCache.getUserFromCache(username);
    	if(user == null){
    		user  = userDao.getUser(username);
    		if (user==null) {
    			throw new UsernameNotFoundException("用户:"+username+"不存在");
			}
    	}
    	userCache.putUserInCache(user);
		return user;
	}
    /**
	 * 获得用户所有角色的权限集合.
	 */
	 Set<GrantedAuthority> obtainGrantedAuthorities(User user) {
		Set<GrantedAuthority> authSet = Sets.newHashSet();
		for (Role role : user.getRoleList()) {
			for (Sysmenu authority : role.getMenuList()) {
				authSet.add(new SimpleGrantedAuthority(authority.getPrefixedName()));
			}
		}
		return authSet;
	}
}
